var express = require("express");
var router = express.Router();

var multiparty = require("multiparty");

const { promisify } = require("util");
const fs = require("fs");

const { uploadImage } = require("../../utils/common");

router.post("/", (req, res) => {
  var multipart = new multiparty.Form();
  multipart.parse(req, async function (err, fields, files) {
    let uploadPromises = [];
    files.file.forEach((file) => {
      const uploadPromise = new Promise(async (resolve) => {
        let lastDotIndex = file.originalFilename.lastIndexOf(".");
        let type = file.originalFilename.slice(lastDotIndex + 1);
        let name = file.originalFilename.slice(0, lastDotIndex);
        const readFile = promisify(fs.readFile);
        const fileBuffer = await readFile(file.path);
        let result = await uploadImage(fileBuffer, type, name);
        resolve(result);
      });

      uploadPromises.push(uploadPromise);
    });

    Promise.all(uploadPromises).then((results) => {
      res.send({
        code: 0,
        message: "upload Successfully",
        data: results,
      });
    });
  });
});
module.exports = router;
